package dao;

import java.util.List;

import hibernateUtils.HibernateUtil;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import beans.ComandaBean;

public class HibernateComandaDAO {
	private static HibernateComandaDAO instancia;
	private static SessionFactory sf;

	private HibernateComandaDAO() {

	}

	public static HibernateComandaDAO getInstancia() {
		if (instancia == null) {
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateComandaDAO();
		}
		return instancia;
	}

	public void grabarComanda(ComandaBean comanda) {
		Session sesion = sf.openSession();
		sesion.beginTransaction();
		sesion.persist(comanda);
		sesion.flush();
		sesion.getTransaction().commit();
		sesion.close();

	}

	public ComandaBean buscarComanda(ComandaBean comandaBean) {
		Session session = sf.openSession();
		ComandaBean c = (ComandaBean) session.get(ComandaBean.class,
				comandaBean.getIdComanda());
		session.close();
		return c;
	}

	public void updateItemsComanda(ComandaBean comandaBean) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.update(comandaBean);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}

	public ComandaBean buscarUltimaComanda() {
		Session session=sf.openSession();
		session.beginTransaction();
		List<ComandaBean>comandas=(List<ComandaBean>)session.createQuery("from ComandaBean").list();
		return comandas.get(comandas.size()-1);
	}

	public void merge(ComandaBean cb) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.merge(cb);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
}
